﻿<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件下载中心</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Microsoft YaHei', sans-serif;
        }

        body {
            background: #f5f5f5;
            padding: 15px;
            color: #333;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        header {
            background: linear-gradient(135deg, #1e88e5, #0d47a1);
            color: white;
            padding: 20px;
            text-align: center;
        }

        h1 {
            font-size: 20px;
            margin-bottom: 5px;
        }

        .control-panel {
            padding: 15px;
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
        }

        .batch-control {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .file-list {
            padding: 0;
        }

        .file-item {
            display: flex;
            align-items: center;
            padding: 15px;
            border-bottom: 1px solid #e9ecef;
            transition: background 0.2s;
        }

            .file-item:hover {
                background: #f8f9fa;
            }

        .file-checkbox {
            margin-right: 15px;
            width: 20px;
            height: 20px;
        }

        .file-info {
            flex: 1;
        }

        .file-name {
            font-weight: 500;
            margin-bottom: 5px;
            color: #333;
        }

        .file-meta {
            font-size: 12px;
            color: #666;
            display: flex;
            gap: 15px;
        }

        .download-count {
            color: #1e88e5;
            font-weight: bold;
        }

        .download-btn {
            background: #1e88e5;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
        }

            .download-btn:hover {
                background: #1976d2;
            }

        .batch-download-btn {
            background: #43a047;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
        }

            .batch-download-btn:disabled {
                background: #ccc;
                cursor: not-allowed;
            }

        .select-all {
            margin-right: 10px;
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #666;
        }

        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }

        .error-message {
            background: #ffebee;
            color: #c62828;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>文件下载中心</h1>
            <p>选择文件进行下载</p>
        </header>

        <div class="error-message" id="errorMessage"></div>

        <div class="control-panel">
            <div class="batch-control">
                <input type="checkbox" id="selectAll" class="select-all">
                <label for="selectAll">全选</label>
                <span>已选择 <span id="selectedCount">0</span> 个文件</span>
            </div>
            <button id="batchDownloadBtn" class="batch-download-btn" disabled>批量下载</button>
        </div>

        <div class="file-list" id="fileList">
            <div class="loading">加载中...</div>
        </div>
    </div>

    <script>
        // API基础URL - 根据实际部署修改
        const API_BASE_URL = 'https://your-api-domain.com/api';

        // 存储文件数据
        let files = [];
        let selectedFiles = new Set();

        // DOM元素
        const fileList = document.getElementById('fileList');
        const selectAll = document.getElementById('selectAll');
        const selectedCount = document.getElementById('selectedCount');
        const batchDownloadBtn = document.getElementById('batchDownloadBtn');
        const errorMessage = document.getElementById('errorMessage');

        // 初始化
        async function init() {
            // 加载文件列表
            await loadFileList();

            
            // 全选/取消全选
            selectAll.addEventListener('change', function ()
            {

                
                const checkboxes = document.querySelectorAll('.file-checkbox');
                console.log("33333333----------" + selectAll);

                checkboxes.forEach(checkbox => {
                    checkbox.checked = this.checked;
                    const fileId = checkbox.dataset.fileId;

                    console.log("4----------[" + fileId);



                    if (this.checked) {
                        selectedFiles.add(fileId);
                    } else {
                        selectedFiles.delete(fileId);
                    }
                });
                updateSelectionInfo();
            });

            // 批量下载
            batchDownloadBtn.addEventListener('click', downloadBatchFiles);
        }

        // 显示错误信息
        function showError(message) {
            errorMessage.textContent = message;
            errorMessage.style.display = 'block';
            setTimeout(() => {
                errorMessage.style.display = 'none';
            }, 5000);
        }

        // 加载文件列表
        async function loadFileList() {
            try {

                //const response = await fetch(`${API_BASE_URL}/files`);
                //if (!response.ok) {
                //    throw new Error('加载文件列表失败');
                //}

                //files = await response.json();


                // 这里应该是从服务器获取文件列表的AJAX请求
                // 模拟数据
                files = [
                    { id: 'file1', name: '文档1.pdf', downloadCount: 15 },
                    { id: 'file2', name: '报告2.pdf', downloadCount: 8 },
                    { id: 'file3', name: '数据3.pdf', downloadCount: 23 },
                    { id: 'file4', name: '分析4.pdf', downloadCount: 11 }
                ];



                renderFileList();
            } catch (error) {
                showError('加载文件失败: ' + error.message);
                fileList.innerHTML = '<div class="empty-state">加载失败</div>';
            }

          


        }

        // 渲染文件列表
        function renderFileList() {
            if (files.length === 0) {
                fileList.innerHTML = '<div class="empty-state">暂无文件</div>';
                return;
            }

            fileList.innerHTML = '';
            files.forEach(file => {
                const fileItem = createFileItem(file);
                fileList.appendChild(fileItem);
            });
        }

        // 创建文件项
        function createFileItem(file) {
            const fileItem = document.createElement('div');
            fileItem.className = 'file-item';

            fileItem.innerHTML = `
                    <input type="checkbox" class="file-checkbox" data-file-id="${file.id}">
                    <div class="file-info">
                        <div class="file-name">${file.originalName}</div>
                        <div class="file-meta">
                            <span class="download-count">下载次数: ${file.downloadCount}</span>
                            <span>上传时间: ${new Date(file.createTime).toLocaleDateString()}</span>
                        </div>
                    </div>
                    <button class="download-btn" data-file-id="${file.id}">下载</button>
                `;

            // 复选框事件
            const checkbox = fileItem.querySelector('.file-checkbox');
            checkbox.addEventListener('change', function () {
                if (this.checked) {
                    selectedFiles.add(file.id);
                } else {
                    selectedFiles.delete(file.id);
                    selectAll.checked = false;
                }
                updateSelectionInfo();
            });

            // 单个下载按钮事件
            const downloadBtn = fileItem.querySelector('.download-btn');
            downloadBtn.addEventListener('click', function () {
                downloadSingleFile(file.id);
            });

            return fileItem;
        }

        // 更新选择信息
        function updateSelectionInfo() {
            selectedCount.textContent = selectedFiles.size;
            batchDownloadBtn.disabled = selectedFiles.size === 0;
            selectAll.checked = selectedFiles.size === files.length && files.length > 0;
        }

        // 下载单个文件
        async function downloadSingleFile(fileId) {
            try {
                const response = await fetch(`${API_BASE_URL}/files/download/single`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ fileIds: [fileId] })
                });

                if (!response.ok)
                {
                    const error = await response.json();
                    throw new Error(error.message || '下载失败');
                }

                // 获取文件名
                const contentDisposition = response.headers.get('Content-Disposition');
                let fileName = `download_${fileId}.pdf`;
                if (contentDisposition) {
                    const match = contentDisposition.match(/filename="?(.+)"?/);
                    if (match) fileName = match[1];
                }

                // 创建Blob并下载
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = fileName;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);

                // 更新下载次数显示
                await updateDownloadCountDisplay(fileId);

            } catch (error) {
                showError('下载失败: ' + error.message);
            }
        }

        // 批量下载文件
        async function downloadBatchFiles() {
            if (selectedFiles.size === 0) return;

            const fileIds = Array.from(selectedFiles);

            try {
                const response = await fetch(`${API_BASE_URL}/files/download/batch`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ fileIds: fileIds })
                });

                if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.message || '批量下载失败');
                }

                // 获取内容类型和文件名
                const contentType = response.headers.get('Content-Type');
                const contentDisposition = response.headers.get('Content-Disposition');
                let fileName = `batch_download_${Date.now()}.zip`;
                if (contentDisposition) {
                    const match = contentDisposition.match(/filename="?(.+)"?/);
                    if (match) fileName = match[1];
                }

                // 创建Blob并下载
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = fileName;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);

                // 更新所有选中文件的下载次数显示
                for (const fileId of fileIds) {
                    await updateDownloadCountDisplay(fileId);
                }

                // 清空选择
                selectedFiles.clear();
                updateSelectionInfo();
                document.querySelectorAll('.file-checkbox').forEach(cb => cb.checked = false);

            } catch (error) {
                showError('批量下载失败: ' + error.message);
            }
        }

        // 更新下载次数显示
        async function updateDownloadCountDisplay(fileId) {
            try {
                const response = await fetch(`${API_BASE_URL}/files/download/count/${fileId}`, {
                    method: 'POST'
                });

                if (response.ok) {
                    const newCount = await response.json();
                    const fileElement = document.querySelector(`[data-file-id="${fileId}"]`);
                    if (fileElement) {
                        const countElement = fileElement.closest('.file-item').querySelector('.download-count');
                        if (countElement) {
                            countElement.textContent = `下载次数: ${newCount}`;
                        }
                    }
                }
            } catch (error) {
                console.error('更新下载次数显示失败:', error);
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html>